package yy.robot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;
import yy.robot.domain.Paging;
import yy.robot.domain.Response;
import yy.robot.domain.User;
import yy.robot.service.UserService;

/**
 * Created by BaiJiFeiLong@gmail.com at 2018/5/3 11:13
 */
@RestController
@RequestMapping("/users")
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public Response<Paging<User>> index(
            @RequestParam(required = false, defaultValue = "0") int page,
            @RequestParam(required = false, defaultValue = "10") int size
    ) {
        Page<User> userPage = userService.findAll(PageRequest.of(page, size));
        return new Response<>(Paging.fromPage(userPage));
    }

    @PostMapping
    public User create(
            @RequestParam String username,
            @RequestParam String password
    ) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        return userService.create(user);
    }

    @GetMapping("{id}")
    public User show(@PathVariable long id) {
        return userService.findById(id);
    }

    @PatchMapping("{id}")
    public User update(
            @PathVariable long id,
            User user
    ) {
        user.setId(id);
        return userService.update(user);
    }

    @DeleteMapping("{id}")
    public void delete(@PathVariable long id) {
        userService.destroy(id);
    }
}
